<template>
  <div class="stepBox">
    <div
      class="cont"
      ref="cont"
    >
      <batch-operat-btn
        v-if="editable"
        :isView="false"
        :addData="false"
        addText='选择商品'
        @onAddData="onAddData"
      >
        <template #cusBtn> </template>
      </batch-operat-btn>
      <div class="recordBox">
        <a-list-table
          :columns="columns"
          :inputName="inputName"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="false"
          :loading="loading"
          :scroll="{ y: null ,scrollToFirstRowOnChange:true,}"
          @onAction="onAction"
          @onChangeInput="onChangeInput"
          @onTableChange="handleTableChange"
        >
        </a-list-table>
      </div>
    </div>
    <div
      class="btnBox"
      v-if="isNew"
    >
      <a-button
        class="btn"
        style="marginRight:20px"
        type="default"
        @click="previous()"
      >
        上一步
      </a-button>
      <a-button
        class="btn"
        type="primary"
        @click="nexts()"
      >
        提交
      </a-button>
    </div>
  </div>
</template>

<script> 
import basicModal from '@/views/app/biz/common/basicModal'
import aListTable from '@/views/app/biz/common/aListTable'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
// import { getInfoByPid as getSupplierInfoByPid } from '@/views/app/biz/supplier/supplier'
import { saveOederGoods } from './saleDelivery'
import {
  getDetailByConditions,
  getDetailByConditionsCount,
} from '../saleOrder/saleOrder'

export default {
  components: {
    basicModal,
    aListTable,
    batchOperatBtn,
  },
  props: {
    //上一步提交的信息
    orderData: {
      type: Object,
    },
    orRrecord: {
      type: Object,
    }
  },
  data () {
    return {
      footer: undefined,
      editable: true,
      loading: false,
      modal: {
        modalVisible: false,
        modalTitle: '添加商品',
        modalWidth: '1000px',
      },

      columns: [
        { title: '采购单位名称', dataIndex: 'customerName', key: 'customerName', align: 'center', },
        { title: '配送单号', dataIndex: 'deliveryOrderNo', key: 'deliveryOrderNo', align: 'center', },
        { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
        // { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
        { title: '订单号', dataIndex: 'purOrderNo', key: 'purOrderNo', align: 'center', },
        { title: '生产厂家名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
        { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
        // { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
        { title: '批号', dataIndex: 'batchCode', key: 'batchCode', align: 'center', width: '150px', scopedSlots: { customRender: 'batchCode' } },
        // { title: '效期', dataIndex: 'expiryDate', key: 'expiryDate', align: 'center' },
        { title: '配送数量', dataIndex: 'num', key: 'num', align: 'center', width: '100px', scopedSlots: { customRender: 'num' } },
        // { title: '备货数量', dataIndex: 'readyNum', key: 'readyNum', align: 'center',width:'100px',scopedSlots: { customRender: 'readyNum' } },
        { title: '单品含税价', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', },
        { title: '状态', dataIndex: 'deliveryState', key: 'deliveryState', align: 'center' },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          key: 'operation',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '5', '10', '100'],
        all: true
      },
      inputName: ['batchCode', 'num'],
      isNew: true,
      listdata: [],
      listKey: 0,
      changeList: [],
      pid: '',
      sysSeq: 0,
      loadings: false,
      order: {},
      q_formDatas: {
        saleOrderPid: this.orRrecord.pid,
      },
      keys: 1
    }
  },
  computed: {},
  mounted () {
    this.q_formDatas.saleOrderPid = this.orRrecord.pid
    this.getTotal()
    this.getList(this.q_formDatas)
  },
  watch: {
    orderData: {
      handler: function (val, oldVal) {
        console.log(this.orderData);
        this.order = this.orderData
        this.getTotal()
        this.getList(this.q_formDatas)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      const paginations = { ...this.pagination }
      paginations.current = pagination.current
      paginations.pageSize = pagination.pageSize
      this.pagination = paginations
      // this.getList(this.q_formDatas)
    },
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getDetailByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      this.loading = true
      let listdata = []
      let res = ''
      res = await getDetailByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        this.orgList = res.data
        for (let item of resdata) {
          listdata.push({
            key: item.pid,
            btnKeys: '添加',
            btnTips: '点击添加该产品的其它批号',
            action: ['添加批号', '无货'],
            pid: '',
            sysSeq: 0,
            purOrderNo: this.orRrecord.purOrderNo,
            customerName: this.orRrecord.customerName,
            customerOrgPid: this.orRrecord.customerOrgPid,
            deliveryOrderPid: this.order.pid,
            deliveryOrderNo: this.order.deliveryOrderNo,
            deliveryState: '待配送',
            saleGoodsPid: item.pid,
            productNameZh: item.productNameZh,
            commonName: '',
            model: item.model,
            spec: item.spec,
            manufacturerZh: item.manufacturerZh,
            batchCode: '',
            expiryDate: '',
            num: item.num,
            // readyNum: null,
            iunitprice: item.iunitprice,
          }
          )
        }
        this.listdata = listdata
        console.log();
      } else {
        this.listdata = []
      }
    },
    // 关闭模态详细框
    closeModal () {
      this.modal.modalVisible = false
      this.$emit('close')
    },
    //点击选择商品
    onAddData () {
    },
    previous () {
      this.$emit("onCancel")
    },
    skip () {
      this.$emit("onSkip", 4)
    },
    nexts () {
      if (this.listdata.length) {
        let listdata = JSON.parse(JSON.stringify(this.listdata))
        for (const item of listdata) {
          delete item.action;
          if (item.num <= 0) {
            this.$message.warn({ content: '产品数量必须大于0', duration: 2 })
            return
          }
          if (!item.batchCode) {
            this.$message.warn({ content: '产品批号不能为空', duration: 2 })
            return
          }
        }
        // this.$emit('onSubmit')
        this.saveObjInfo(listdata)
      } else {
        this.$message.warn({ content: '暂未添加任何商品', duration: 2 })
      }
    },
    //修改列表信息aList为修改的记录
    onChangeInput (aList) {
    },
    // 保存详细信息
    async saveObjInfo (val) {
      console.log(val)
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      let res = await saveOederGoods(val)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '提交成功', key, duration: 3 })
        this.closeModal()
        this.$emit('onSubmit')
      } else {
        this.$message.error({ content: '提交失败,请稍后再试', key, duration: 3 })
      }
    },
    onAction (text, record, index) {

      console.log(text, record, index)
      if (text == '无货') {
        this.listdata.splice(index, 1)
      } else if (text == '添加批号') {
        this.keys++
        let newRecord = JSON.parse(JSON.stringify(record))
        newRecord.action = ['移除']
        // newRecord.readyNum=null
        newRecord.num = null
        newRecord.batchCode = null
        newRecord.key += '-' + this.keys
        const pagination = { ...this.pagination }
        pagination.total++
        if (index + 1 == pagination.pageSize) {
          pagination.current++
          this.$refs.cont.scrollTop = 0
          // console.log(this.$refs.cont.scrollTop);
        }
        this.pagination = pagination
        let optInd = this.listdata.findIndex(item => {
          return item.key == record.key
        })
        this.listdata.splice(optInd + 1, 0, newRecord)
        this.listdata = this.listdata
        console.log(this.listdata);

        console.log(this.listdata);
      } else if (text == '移除') {
        let optInd = this.listdata.findIndex(item => {
          return item.key == record.key
        })
        this.listdata.splice(optInd, 1)
        this.listdata = this.listdata
        const pagination = { ...this.pagination }
        pagination.total--
        this.pagination = pagination
      }
    },
  },
}
</script>

<style>
.recordBox {
  width: 100%;
  min-height: 80px;
}
.stepBox {
  width: 100%;
  height: 100%;
  position: relative;
}
.cont {
  padding-left: 5px;
  max-height: calc(70vh - 40px);
  overflow-y: scroll;
}
.btnBox {
  height: 7vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  /* border: 1px solid #eee; */
  position: absolute;
  bottom: 0px;
}
</style>